﻿using LightWadf.Core.Configuration;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace LightWadf.Core.Util
{
    public class Utility
    {
        private static Assembly assembly = null;
        public static Assembly Assembly
        {
            get
            {
                if(assembly == null)
                {
                    assembly = Assembly.Load(new AssemblyName(Utility.HostingEnvironment.ApplicationName));
                }
                return assembly;
            }
        }

        private static AbstractGlobalConfiguration globalConfiguration = null;
        public static AbstractGlobalConfiguration GlobalConfiguration
        {
            get
            {
                if (Utility.globalConfiguration == null)
                {
                    foreach (Type type in Utility.Assembly.ExportedTypes)
                    {
                        // 如果 type 实现了 IGlobalConfiguration 接口
                        if (typeof(AbstractGlobalConfiguration).IsAssignableFrom(type))
                        {
                            try
                            {
                                globalConfiguration = Activator.CreateInstance(type) as AbstractGlobalConfiguration;
                                break;
                            }
                            catch (Exception e)
                            {
                                continue;
                            }
                        }
                    }
                    if(globalConfiguration == null)
                    {
                        globalConfiguration = new GlobalConfiguration();
                    }
                }
                return Utility.globalConfiguration;
            }
        }

        public static IHostingEnvironment HostingEnvironment = null;
    }
}
